import { Reducer } from "redux";
import actionTypes from "../../store/actions/actionTypes";
import dayjs from "dayjs";
import { SettingsI, WeixinOauthI, UserI } from "../../types/system";
import { ModelParamsI } from "../../types/api";
import {
  setModelParamsAction,
  setSettingsAction,
  setUserAction,
  setWeixinOauthAction,
} from "../actions";

const initialSettings: SettingsI = {
  collapsedMenu: true,
  allowUpload: false,
  network: "LAN",
  breadcrumbs: [{ label: "首页", key: "/" }],
};

export const settingsReducer: Reducer<
  SettingsI,
  ReturnType<typeof setSettingsAction>
> = (state = initialSettings, action: ReturnType<typeof setSettingsAction>) => {
  switch (action.type) {
    case actionTypes.SET_SETTINGS: {
      return Object.assign({}, state, action.payload);
    }
    default:
      return state;
  }
};

const initialWeixinOauth: WeixinOauthI = {
  id: "",
  oauthType: "",
  openid: "",
  nickname: "",
  sex: 0,
  province: "",
  city: "",
  country: "",
  headimgurl: "",
  privileges: "",
  unionid: "",
  deleteFlag: false,
  sign: "",
  userID: "",
};

export const weixinOauthReducer = (
  state = initialWeixinOauth,
  action: ReturnType<typeof setWeixinOauthAction>
) => {
  switch (action.type) {
    case actionTypes.SET_WEIXIN_OAUTH: {
      return Object.assign({}, state, action.payload);
    }
    default:
      return state;
  }
};

export const initialUser: UserI = {
  id: "",
  token: "",
  username: "",
  cellphone: "",
  email: "",
  nickname: "",
  lastName: "",
  firstName: "",
  fullName: "",
  birthday: dayjs().format(),
  password: "",
  sex: 0,
  score: 0,
  avatarURL: "",
  lastLoginAt: dayjs().format(),
  isActive: false,
  isSuperuser: false,
  currentRole: undefined,
  roleUsers: [],
  // tenantID: "",
  // tenant: null,
  resources: [],
};

export const userReducer = (
  state = initialUser,
  action: ReturnType<typeof setUserAction>
) => {
  switch (action.type) {
    case actionTypes.SET_USER: {
      return Object.assign({}, state, action.payload);
    }
    default:
      return state;
  }
};

// 模型参数
export const initialModelParams: ModelParamsI = {
  initReservoirCapacity: 2880,
  reservoirDecayFactor: 0.5,
  sleepDebtFactor: 0.0026564,
  circadianFactor: 0.55,
  sleepInertiaFactor: 0.04,
  sleepInertiaMax: 0.05,
  sleepInertiaFactorT: 0.00312,
  circadian24Peak: 18,
  circadian12Peak: 3,
  circadian12Factor: 0.5,
  a1: 0.07,
  a2: 0.05,
  k1: 0.22,
  k2: 0.5,
  k3: 0.0015,
  sleepHour: 0.0,
  awakeHour: 8.0,
};

export const modelPramsReducer = (
  state = initialModelParams,
  action: ReturnType<typeof setModelParamsAction>
) => {
  switch (action.type) {
    case actionTypes.SET_MODEL_PARAMS: {
      if (JSON.stringify(action.payload) === "{}") {
        return initialModelParams;
      }
      return Object.assign({}, state, action.payload);
    }
    default:
      return state;
  }
};
